﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Common
{
    public static class ExtendMethod
    {

        /// <summary>
        /// 把来源的属性拷贝到目标上
        /// 浅复制
        /// </summary>
        /// <typeparam name="S">来源类型</typeparam>
        /// <typeparam name="R">目标类型</typeparam>
        /// <param name="source">来源对象</param>
        /// <param name="target">目标对象</param>
        /// <param name="filterNull">是否过滤NULL</param>
        public static void PropertiesCopyTo<S, R>(this S source, R target)
            where R : class, new()
            where S : class, new()
        {

            PropertiesCopyTo(source, target, false);
        }


        /// <summary>
        /// 把来源的属性拷贝到目标上
        /// 浅复制
        /// </summary>
        /// <typeparam name="S">来源类型</typeparam>
        /// <typeparam name="R">目标类型</typeparam>
        /// <param name="source">来源对象</param>
        /// <param name="target">目标对象</param>
        /// <param name="filterNull">是否过滤NULL</param>
        public static void PropertiesCopyTo<S, R>(this S source, R target, bool filterNull)
        {
            if (source == null)
            {
                target = default(R);
                return;
            }

            Type rType = typeof(R);
            Type sType = typeof(S);


            PropertyInfo[] rInfos = rType.GetProperties();
            PropertyInfo[] sInfos = sType.GetProperties();

            PropertyInfo temp = null;

            object value = null;
            foreach (var p in rInfos)
            {
                if (!p.CanWrite)
                    continue;
                //基础类型操作
                if (p.PropertyType == typeof(string) || p.PropertyType.IsValueType)
                {
                    temp = sInfos.FirstOrDefault(pinfo => pinfo.Name == p.Name);
                    if (temp != null)
                    {
                        value = temp.GetValue(source, null);
                        //可能要类型转换 暂时不写

                        if (value == null && filterNull)
                            continue;

                        p.SetValue(target, value, new object[0]);

                    }
                }
            }

        }

        public static void AddNotExist<T>(this List<T> list, T o1)
        {
            if (list == null)
                return;
            if(!list.Contains(o1))
            {
                list.Add(o1);
            }
        }
    }
}
